/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.controller;

import com.db.Conector;
import com.db.SqlManager;
import com.exception.DataException;
import com.javabeans.Estudiante;
import com.javabeans.RolUsuario;
import com.javabeans.Usuario;
import com.model.AccesoManager;
import com.model.CarreraEstudianteManager;
import com.model.EstudianteManager;
import com.model.ManagerFactory;
import com.model.RolUsuarioManager;
import com.model.UsuarioManager;
import com.util.UtilDate;
import java.io.IOException;
import java.sql.Connection;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @author Administrador
 */
public class Principal extends HttpServlet {

    HttpServletRequest request;
    HttpServletResponse response;
    HttpSession session;
    String msg = "";
    boolean isRedirect = true; // inicializamos con sendRedirect....
    
    public static String PAGE = "";
    public static final String ERROR_PAGE = "error.jsp";
    
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        this.request = request;
        this.response = response;
        int accion = 0;
        accion = Integer.parseInt(request.getParameter("accion"));
        try{
            switch(accion){
                case 1 : iniciaSesionEst(request,response); break;          //  1 = valida estudiante
                case 2 : cerrarSessionEst(request,response); break;         //  2 = cierra sesion estudiante
                case 3 : iniciaSesionDoc(request,response); break;          //  3 = validar docente
                case 4 : cerrarSessionDoc(request,response); break;         //  4 = cierra session docente
                case 5 : iniciaSesionAdministr(request,response); break;         //  4 = cierra session docente
                case 6 : cerrarSessionAdministr(request,response); break;         //  4 = cierra session docente
            }
        }catch(DataException e){
            throw new ServletException(e);
        }
        if(isRedirect){
            response.sendRedirect(PAGE);
        }else{
            RequestDispatcher dispatch = request.getRequestDispatcher(PAGE);
            dispatch.forward(request,response);
        }
    }
    
    private void iniciaSesionEst(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, DataException{
        // accion <-- 1
        Connection c = null;
        
        int idEstudiante = Integer.parseInt(request.getParameter("v1"));
        String ci = request.getParameter("v2").trim();
        try{
            c = Conector.getConexion();
            EstudianteManager estManager = ManagerFactory.getEstudianteManagerInstance(c);
            CarreraEstudianteManager ceManager = ManagerFactory.getCarreraEstudianteManagerInstance(c);
            String ip = request.getRemoteAddr();            
            Estudiante e = estManager.validarEstudiante(idEstudiante, ci);           
            if(e.getIdEstudiante() != 0){
                session = request.getSession(true);
                request.setAttribute("carreras", ceManager.getCarreras(idEstudiante, ci));// esto es para recuperar sus carreras
                session.setAttribute("s_estudiante", e);
                PAGE = "WEB-INF/ESTUDIANTE/portada.jsp";
                isRedirect = false;                
            }else{
                msg = "C&oacute;digo o C.I. incorrecto! vuelva a intentarlo!";                
                PAGE = "web/index.jsp?tipo=4&msg="+msg;
            }
        }catch(DataException e){
            System.out.println("Error al iniciar session estudiante "+UtilDate.getDateTime()+" Principal -> iniciaSesionEst() "+e.getMessage());
        }catch(Exception ex){
            System.out.println("Error al iniciar session estudiante "+UtilDate.getDateTime()+" Principal -> iniciaSesionEst() "+ex.getMessage());
        }finally{
            SqlManager.closeConexion(c);
        }
    }
    
    private void cerrarSessionEst(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        // accion <-- 2
        PAGE = "web/index.jsp";
        session = request.getSession(true);
        if(session.getAttribute("s_estudiante") != null){
            session.invalidate(); // finalmente eliminamos la session actual
        }
    }
    
    private void iniciaSesionDoc(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, DataException{
        // accion <-- 3
        Connection c = null;
        String login = request.getParameter("v3").trim();
        String password = request.getParameter("v4").trim();       
        try{
            c = Conector.getConexion();
            UsuarioManager docenteManager = ManagerFactory.getUsuarioManagerInstance(c);
            String ip = request.getRemoteAddr();           
            Usuario uDocente = docenteManager.validarDocente(login, password);           
            if(uDocente.getIdUsuario() != 0){
                session = request.getSession(true);
                session.setAttribute("s_docente", uDocente);
                PAGE = "WEB-INF/DOCENTE/portada.jsp";
                isRedirect = false;
            }else{
                msg = "Login o password incorrecto! vuelva a intentarlo!";               
                PAGE = "web/index.jsp?tipo=3&msg="+msg;
            }
        }catch(DataException e){
            System.out.println("Error al iniciar session docente "+UtilDate.getDateTime()+" Principal -> iniciaSesionDoc() "+e.getMessage());
        }catch(Exception ex){
            System.out.println("Error al iniciar session docente "+UtilDate.getDateTime()+" Principal -> iniciaSesionDoc() "+ex.getMessage());
        }finally{
            SqlManager.closeConexion(c);
        }
    }
    
    private void cerrarSessionDoc(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        // accion <-- 4
        PAGE = "web/index.jsp";
        session = request.getSession(true);
        if(session.getAttribute("s_docente") != null){
            session.invalidate(); // finalmente eliminamos la session actual
        }
    }
    
    private void iniciaSesionAdministr(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, DataException{
        // accion <-- 5
        Connection c = null;
        String login = request.getParameter("v5").trim();
        String password = request.getParameter("v6").trim();
        
        String ips = null;
        String host = null;
        ips = request.getRemoteAddr();
        host = request.getRemoteHost();
        String ip2 = java.net.InetAddress.getLocalHost().getHostAddress ();       
        try{
            c = Conector.getConexion();
            RolUsuarioManager r_umanager = ManagerFactory.getRolUsuarioManagerInstance(c);
            AccesoManager amanager = ManagerFactory.getAccesoManagerInstance(c);
            String ip = request.getRemoteAddr();            
            RolUsuario r_u = r_umanager.validarUsuario(login, password);           
            if(r_u.getIdUsuario() != 0){
                session = request.getSession(true);
                session.setAttribute("s_accesos", amanager.getAccesos(r_u.getIdUsuario(), r_u.getIdRol()));
                session.setAttribute("s_Usuario", r_u.getUsuario());
                session.setAttribute("s_Rol", r_u.getRol());
                PAGE = "WEB-INF/ADMINISTRATIVO/portada.jsp";
                isRedirect = false;
            }else{
                msg = "Login o password incorrecto! vuelva a intentarlo!";                
                PAGE = "web/index.jsp?tipo=2&msg="+msg;               
            }
        }catch(DataException e){
            System.out.println("Error al iniciar session administrativo "+UtilDate.getDateTime()+" Principal -> iniciaSesionAdministr() "+e.getMessage());
        }catch(Exception ex){
            System.out.println("Error al iniciar session administrativo "+UtilDate.getDateTime()+" Principal -> iniciaSesionAdministr() "+ex.getMessage());
        }finally{
            SqlManager.closeConexion(c);
        }
    }
    
    private void cerrarSessionAdministr(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        // accion <-- 6
        PAGE = "web/index.jsp";
        session = request.getSession(true);
        if(session.getAttribute("s_Usuario") != null){
            session.invalidate(); // finalmente eliminamos la session actual
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
